import axios from 'axios'
import Storeage from "./StorageUtil"
import Elmentui from "element-ui"
import store from "@/store"
import router from "@/router"
import Cookies from 'js-cookie'
import {
  encrypt,
  decrypt
} from "./secret"

function genter(token) {
  let result = {
    index: [],
    key: ''
  };
  while (true) {
    let i = Math.floor(Math.random() * token.length);
    if (result.key.indexOf(result[i]) == -1) {
      result.key += token[i]
      result.index.push(i)
    }
    if (result.key.length == 8) break;
  }
  result.index = result.index.toString();
  return result;
}

const service = axios.create({
  baseURL: "/game",
  withCredentials: true, //跨域凭证
  timeout: 5000
})

let writeList = ['/user/upload_file']

service.interceptors.request.use(
  config => {
    if (Cookies.get('token')) {
      if (writeList.indexOf(config.url) == -1) {
        let token = Cookies.get('token'),result = genter(token);
        if (config.method == 'post' && config.data) {
          config.headers['absolute'] = encrypt(result.index, 'LGYNDZJN')
          config.data = encrypt(JSON.stringify(config.data), result.key)
        }
      }
      config.headers['Authorization'] = 'Bearer ' + Cookies.get('token')
      config.headers['Content-Type'] = 'application/json'
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    let res = response.data
    if (typeof res != "object") {
      if (!Cookies.get("token")) res = JSON.parse(decrypt(res, 'LGYNDZJN'));
      else {
        let index = decrypt(response.headers['absolute'], 'LGYNDZJN');
        let indexInfo = index.split(','),
          key = '',
          data = '',
          token = Cookies.get("token");
        indexInfo.map(item => {
          item = item * 1
          key += token[item]
        })
        console.log('下标数组', indexInfo)
        console.log('key:----->' + key)
        console.log('加密数据：', res)
        data = decrypt(res, key)
        res = JSON.parse(data)
        console.log(res)
      }
    }
    if (res.code && res.code !== 200) {
      // 登录超时,重新登录
      if (res.code == '401') {
        router.push({
          path: "/login"
        })
        Cookies.set('Token', "", -1);
        Storeage.Local.clear()
      }
      Elmentui.Message.warning(res.message)
      return Promise.reject(res || 'error')
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default {
  del(url, params) {
    return service({
      method: 'delete',
      url,
      params,
      timeout: 15000
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  post(url, data, key) {
    return service({
      method: 'post',
      url,
      data: key ? encrypt(JSON.stringify(data), key) : data,
      timeout: 15000,
      headers: {
        'content-type': 'application/json;charset=UTF-8'
      }
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  upload(url, data) {
    let form = new FormData()
    Object.keys(data).forEach(value => {
      form.append(value, data[value])
    })
    return service({
      method: 'post',
      url,
      data,
      transformRequest: [function(data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }],
      timeout: 15000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  get(url, params) {
    return service({
      method: 'get',
      url,
      params,
      timeout: 15000
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  put(url, data) {
    return service({
      method: 'put',
      baseURL: process.env.BASE_API,
      url,
      data,
      timeout: 15000
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  time(tamp) {
    return timestampToTime(tamp)
  }
}
